package com.xuan.judge.config;


import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.core.DefaultDockerClientConfig;

import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.netty.NettyDockerCmdExecFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DockerSandBoxPoolConfig {


    @Value("${sandbox.docker.host:tcp://localhost:2375}")
    private String dockerHost;

    @Value("${sandbox.limit.memoryLimit:100000000}")
    private Long memoryLimit;

    @Value("${sandbox.limit.memorySwapLimit:100000000}")
    private Long memorySwapLimit;

    @Value("${sandbox.limit.cpuLimit:1}")
    private Long cpuLimit;

    @Value("${sandbox.docker.image:openjdk:8-jdk-alpine}")
    private String jdkImage;

    @Value("${sandbox.container.name-prefix:oj-sandbox-jdk}")
    private String containerNamePrefix;

    @Value("${sandbox.docker.pool.size:4}")
    private int poolSize;




    @Bean
    public DockerClient createDockerClient() {
        DefaultDockerClientConfig clientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
                .withDockerHost(dockerHost)       // 配置 docker 服务地址，以便连接 docker
                .build();
        return DockerClientBuilder.getInstance(clientConfig)
                .withDockerCmdExecFactory(new NettyDockerCmdExecFactory())
                .build();
    }


    /**
     *  通过创建容器池来管理 docker 容器
     * @return DockerSandBoxPool
     */
    @Bean
    public DockerSandBoxPool createDockerSandBoxPool(DockerClient dockerClient) {
        // 完成容器的相关创建工作,并将 DockerSandBoxPool 对象交由spring容器管理
       return new DockerSandBoxPool(dockerClient, memoryLimit, memorySwapLimit, cpuLimit, jdkImage, containerNamePrefix, poolSize);
    }

}
